package com.czy.seed.mvc.home.controller;

import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.controller.BaseController;
import com.czy.seed.mvc.base.param.Param;
import com.czy.seed.mvc.home.entity.Commodity;
import com.czy.seed.mvc.home.entity.Menu;
import com.czy.seed.mvc.home.entity.MenuVo;
import com.czy.seed.mvc.home.entity.Merchant;
import com.czy.seed.mvc.home.service.CommodityService;
import com.czy.seed.mvc.home.service.MenuService;
import com.czy.seed.mvc.home.service.MerchantService;
import com.czy.seed.mvc.util.Cache;
import com.czy.seed.mvc.util.CacheManager;
import com.czy.seed.mvc.util.Res;
import com.czy.seed.mybatis.base.QueryParams;
import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * @Author: liuyun
 * Created by liuyun  9:47 2017/11/24.
 */


@RestController
@RequestMapping("/home/menu")
public class MenuController extends BaseController<Menu> {

    public static Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    private MenuService menuServic;

    @Autowired
    private CommodityService commodityService;



    @RequestMapping("/select")
    public Res select() {
        String key = CacheManager.findAllEstate;
        List<Menu> listMen;
        Cache cache = CacheManager.getCacheInfo(key);
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        if (null == cache) {
            QueryParams queryParams = new QueryParams(Menu.class);
            listMen = menuServic.selectListByParams(queryParams);
            cache = new Cache();
            cache.setKey(key);
            cache.setValue(listMen);
            CacheManager.putCache(key, cache);
        } else {
            listMen = (List<Menu>) cache.getValue();
        }
        List<MenuVo> listMenu = new ArrayList<MenuVo>();
        for (Menu menu : listMen) {
            MenuVo men = new MenuVo();
            men.setId(menu.getId());
            men.setFatherTypeId(menu.getFatherTypeId());
            men.setMenuGrade(menu.getMenuGrade());
            men.setName(menu.getName());
            men.setUrl(menu.getUrl());
            men.setImage(menu.getImage());
            men.setCoding(menu.getCoding());
            listMenu.add(men);
        }
        List<MenuVo> menuList = new ArrayList<MenuVo>();
        // 先找到所有的一级菜单
        for (int i = 0; i < listMenu.size(); i++) {
            // 一级菜单
            if (listMenu.get(i).getMenuGrade() == 1) {
                menuList.add(listMenu.get(i));
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (MenuVo menu : menuList) {
            menu.setChildMenus(getChild(menu.getId(), listMenu));
        }

        //获取首页商品信息
        List<Object> Comm = new ArrayList<Object>();

        for (int i = 0; i < menuList.size(); i++) {
            HashMap<String, Object> objectObjectHashMap = new HashMap<String, Object>();
            Merchant merchant = new Merchant();
            QueryParams queryParams = new QueryParams(Commodity.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andLike("category", menuList.get(i).getId() + "-%");
            List<Commodity> CommodityList = commodityService.selectPageByParams(0, 8, queryParams);
            objectObjectHashMap.put("name", menuList.get(i).getName());
            objectObjectHashMap.put("image", menuList.get(i).getImage());
            objectObjectHashMap.put("id", menuList.get(i).getId());
            objectObjectHashMap.put("val", CommodityList);
            Comm.add(objectObjectHashMap);
        }
        pageInfo.put("Comm", Comm);
        pageInfo.put("Menu", menuList);
        return Res.ok(pageInfo);
    }

    /**
     * 查询各个级别的菜单信息
     *
     * @param param
     * @return
     */

    @RequestMapping("/selectStair")
    @ResponseBody
    public Res selectStair(int param,Long fatherTypeId) {
        QueryParams queryParams = new QueryParams(Menu.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("menuGrade", param);
        criteria.andEqualTo("fatherTypeId",fatherTypeId);
        List<Menu> page = menuServic.selectListByParams(queryParams);
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("page", page);
        return Res.ok(pageInfo);
    }
    /**
     * 根据菜单ID查询菜单信息
     *
     * @param param
     * @return
     */

    @RequestMapping("/selectMenuById")
    @ResponseBody
    public Res selectMenuById(Long id) {
        QueryParams queryParams = new QueryParams(Menu.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("id", id);;
        List<Menu> page = menuServic.selectListByParams(queryParams);
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("page", page);
        return Res.ok(pageInfo);
    }

    /**
     * 修改菜单信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/updateEntity")
    public Res updateEntity(HttpServletRequest request) {
        String entity = request.getParameter("entity");
        try {
            Menu menu = JSONObject.parseObject(entity, Menu.class);
            menuServic.updateByPrimaryKey(menu);
        } catch (Exception e) {
            logger.error("修改菜单信息失败~!", e);
            return Res.error();
        }
        return Res.ok();
    }

    /**
     * 添加菜单信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/insertEntity")
    public Res insertEntity(HttpServletRequest request) {
        String entity = request.getParameter("entity");
        try {
            Menu menu = JSONObject.parseObject(entity, Menu.class);

            menuServic.insert(menu);
        } catch (Exception e) {
            logger.error("添加菜单信息失败~!", e);
            return Res.error();
        }

        return Res.ok();
    }


    /**
     * 删除菜单信息
     * @param
     * @return
     */
    @RequestMapping("/deleteEntity")
    public Res deleteEntity(Long entityId) {
        try {
            menuServic.deleteByPrimaryKey(entityId);
        } catch (Exception e) {
            logger.error("删除菜单信息失败~!", e);
            return Res.error();
        }

        return Res.ok();
    }

    /**
     * 递归查找子菜单
     *
     * @param id       当前菜单id
     * @param rootMenu 要查找的列表
     * @return
     */
    private List<MenuVo> getChild(Long id, List<MenuVo> rootMenu) {
        // 子菜单
        List<MenuVo> childList = new ArrayList<>();
        for (MenuVo menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (menu.getFatherTypeId() != null) {
                if (menu.getFatherTypeId().equals(id)) {
                    childList.add(menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (MenuVo menu : childList) {
            // 递归
            menu.setChildMenus(getChild(menu.getId(), rootMenu));

        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
    //菜单模糊查询
    @RequestMapping("/likeSelect")
    public Res likeSelectFirst(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(Commodity.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        try{
            String Menu =  request.getParameter("Menu");
            Menu menu = JSONObject.parseObject(Menu,Menu.class);
                if(menu.getMenuGrade()==1){
                    criteria.andLike("category", menu.getId()+"%");
                }else if(menu.getMenuGrade()==2){
                    criteria.andLike("category", "%"+menu.getId()+"%");
                }else{
                    criteria.andLike("category", "%"+menu.getId());
                }
            List<Commodity> commodityList = commodityService.selectListByParams(queryParams);
            pageInfo.put("commodityList",commodityList);
            System.out.println("commodityList:"+commodityList);
            logger.info("菜单模糊查询成功："+commodityList.get(0).getCommodityName());
        }catch(Exception e){
            logger.error("菜单模糊查询失败");
        }
        return Res.ok(pageInfo);
    }

}
